/**
 * @file ext-polystar.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */



const name = 'reportdata'
const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}

export default {
  name,
  async init() {
    const svgEditor = this
    const { svgCanvas } = svgEditor
    const { $id, $click, $qq } = svgCanvas
    let lastBBox = {}
    let started
    let newFO
    let p = {
      x1: 0,
      x2: 0,
      y1: 0,
      y2: 0,
      width: 0,
      height: 0,
      rowArr: ["序号", "单位", "簇11111", "簇2", "簇3", "簇4", "簇5", "簇6"],
      colArr: ["U", "I", "Soc", "SOH", "Umax", "Pack", "Umin", 'Pack', 'Tmax', 'Pack', 'Tmin', 'Pack'],
    }
    await loadExtensionTranslation(svgEditor)

    const isGecko = navigator.userAgent.includes('Gecko/')
    const setAttrs = (elem, attrs) => {
      if (isGecko) {
        Object.entries(attrs).forEach(([aname, val]) => {
          elem.setAttribute(aname, val)
        })
      } else {
        Object.entries(attrs).forEach(([aname, val]) => {
          const prop = elem[aname]
          if (prop?.constructor === 'SVGLength') {
            prop.baseVal.value = val
          } else {
            elem.setAttribute(aname, val)
          }
        })
      }
    }

    const createTable = (data, svgId) => {
      let repGroup = svgCanvas.addSVGElementsFromJson({
        element: 'foreignObject',
        attr: {
          x: data.x1,
          y: data.y1,
          width: data.width,
          height: data.height,
          class: 'excelWrap',
          id: "excelWrap_" + svgId
        }
      })


      const { rowArr, colArr } = data;
      // 创建表格元素
      const table = document.createElement('table');

      // 创建表头行
      const headerRow = table.insertRow();
      rowArr.forEach(item => {
        const headerCell = headerRow.insertCell();
        headerCell.textContent = item;
      });

      // 创建数据行和列
      for (let i = 0; i < colArr.length; i++) {
        const dataRow = table.insertRow();

        for (let j = 0; j < rowArr.length; j++) {
          const indexCell = dataRow.insertCell();
          if (j == 0) {
            indexCell.textContent = i + 1; // 数字序号
          } else if (j == 1) {
            indexCell.textContent = colArr[i];
          } else {
            indexCell.textContent = "####,###";
          }
        }
      }

      $(repGroup).empty()
      $(repGroup).append(table);

      return repGroup;




    }

    return {
      name: svgEditor.i18next.t(`${name}:name`),
      // The callback should be used to load the DOM with the appropriate UI items
      callback() {
        // Add the button and its handler(s)
        // Note: the star extension needs to be loaded before the polygon extension
        const titlePolygon = `${name}:buttons.1.title`
        const buttonTemplate = `
              <se-button id="tool_reportdata" title="${titlePolygon}" src="reportdata.svg">
              </se-button>
          `
        svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 8)

        $click($id('tool_reportdata'), () => {
          if (this.leftPanel.updateLeftPanel('tool_reportdata')) {
            svgCanvas.setMode('reportdata')
          }
        })
      },
      mouseDown(opts) {
        if (svgCanvas.getMode() === 'reportdata') {
          started = true
          p.x1 = opts.start_x
          p.y1 = opts.start_y
          p.width = 80;
          p.height = 100;
          newFO = svgCanvas.addSVGElementsFromJson({
            element: 'g',
            attr: {
              class: 'reportdata ems',
              'doc-type': 'reportdata',
              id: svgCanvas.getNextId()
            }
          })

          let excel = createTable(p, newFO.id);
          newFO.append(excel);

          lastBBox = newFO.getBBox()
          return {
            started: true
          }
        }
        return undefined
      },
      sourceChanged(opts) {
        let elem = opts.elems[0];
        if (!elem) return;
        if (elem.tagName === 'svg' && elem.id === 'svgcontent') {
            // Update svgContent (can change on import)
            let svgContent = elem;
            let gWrap  = $(svgContent).find(".reportdata");
            Array.from(gWrap).forEach(function(elem){
                // 如果table标签丢失，则重新创建并添加到foreignObject中
                p = {
                  rowArr: ["序号", "单位", "簇1", "簇2", "簇3", "簇4", "簇5", "簇6"],
                  colArr: ["U", "I", "Soc", "SOH", "Umax", "Pack", "Umin", 'Pack', 'Tmax', 'Pack', 'Tmin', 'Pack'],
                  x1:$(elem).find(".excelWrap").attr('x'),
                  y1:$(elem).find(".excelWrap").attr('y'),
                  width:$(elem).find(".excelWrap").width(),
                  height:$(elem).find(".excelWrap").height()
                };

               
                
                let id = $(elem).attr("id");
                $(elem).empty();
                let excel_table=createTable(p, id);
                $(elem).append(excel_table)

          

            })

          

        }
      },
      mouseMove(opts) {
        if (!started) {
          return undefined;
        }
        const zoom = svgCanvas.getZoom()
        let x = opts.mouse_x / zoom
        let y = opts.mouse_y / zoom
        if (svgCanvas.getMode() === 'reportdata') {
          if (svgCanvas.getCurConfig().gridSnapping) {
            x = svgCanvas.snapToGrid(x)
            y = svgCanvas.snapToGrid(y)
          }
          const tlist = newFO.transform.baseVal
          const box = newFO.getBBox()
          const left = box.x; const top = box.y

          const newbox = {
            width: Math.abs(x - p.x1),
            height: Math.abs(y - p.y1)
          }

          let sx = (newbox.width / lastBBox.width) || 1
          let sy = (newbox.height / lastBBox.height) || 1

          // Not perfect, but mostly works...
          let tx = 0
          if (x < p.x1) {
            tx = lastBBox.width
          }
          let ty = 0
          if (y < p.y1) {
            ty = lastBBox.height
          }

          // update the transform list with translate,scale,translate
          const translateOrigin = svgroot.createSVGTransform()
          const scale = svgroot.createSVGTransform()
          const translateBack = svgroot.createSVGTransform()

          translateOrigin.setTranslate(-(left + tx), -(top + ty))
          scale.setScale(sx, sy)

          translateBack.setTranslate(left + tx, top + ty)
          tlist.appendItem(translateBack)
          tlist.appendItem(scale)
          tlist.appendItem(translateOrigin)


          svgCanvas.recalculateDimensions(newFO);
          svgCanvas.selectorManager.requestSelector(newFO).resize()
          svgCanvas.call('transition', newFO)
          lastBBox = newFO.getBBox()
          return {
            started: true
          }




        }

        return undefined;


      },
      mouseUp() {
        if (svgCanvas.getMode() === 'reportdata') {
          const keep = true;
          return {
            keep,
            element: newFO
          }
        }
        return undefined
      },
      updateReportData(opts) {
        if (opts.mode != "reportdata") {
          return
        }
        let data = opts.data;
        //dosomething
      },
    }
  }
}
